package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CheckOutListContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.DateUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:  外出子表 fragment
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/3/3 11:12
 */
public class CheckOutNewFragment extends BaseFragment {
  protected static final String EXTRA_STATUS =
      "com.isunland.managesystem.ui.CheckOutNewFragment.EXTRA_STATUS";
  protected static String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.CheckOutNewFragment.EXTRA_CONTENT";
  protected static String EXTRA_PID = "com.isunland.managesystem.ui.CheckOutNewFragment.EXTRA_PID";
  protected static String EXTRA_IFLATERWRITER =
      "com.isunland.managesystem.ui.CheckOutNewFragment.EXTRA_IFLATERWRITER";
  protected static String EXTRA_FROM =
      "com.isunland.managesystem.ui.CheckOutNewFragment.EXTRA_FROM";
  private CheckOutListContent mcontent;
  protected static final int ADD = 1;
  protected static final int EDIT = 2;
  protected static final int CHECK = 3;// 审核中或审核通过

  protected static final int REQUEST_ACTUAL_DATE_END = 1;
  protected static final int REQUEST_ACTUAL_DATE_START = 2;
  public static final int REQUEST_DELETE = 3;
  public static final int REQUEST_SUBMIT = 4;
  protected String mPid;
  protected String mId;
  protected String mDataStatus;
  protected String mFrom;
  protected int mMenuType;

  private EditText mEtReason;
  private TextView mTvActualStartTime;
  private TextView mTvActualEndTime;
  private TextView mTvBeginTimeTitle;
  private TextView mTvEndTimeTitle;
  private TextView mTv0utHours;
  private EditText mEtActualHours;
  private String mIfLaterWriter;//是否补填,默认为申请F，不补填

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.requisitionout);

    mcontent = (CheckOutListContent) getArguments().getSerializable(EXTRA_CONTENT);
    mPid = (String) getArguments().getSerializable(EXTRA_PID);
    mIfLaterWriter = (String) getArguments().getSerializable(EXTRA_IFLATERWRITER);
    mFrom = (String) getArguments().getSerializable(EXTRA_FROM);
    if (null == mcontent) {
      //添加
      mMenuType = ADD;
      mId = UUID.randomUUID().toString();
    } else {
      //详情
      mId = mcontent.getId();
      mDataStatus = mcontent.getDataStatus();
      if (null != mDataStatus && (mDataStatus.equalsIgnoreCase("new")
          || mDataStatus.equalsIgnoreCase("abort"))) {
        //草稿终止状态可以修改保存和删除
        mMenuType = EDIT;
      }
      if (null != mDataStatus && (mDataStatus.equalsIgnoreCase("checkPass")
          || mDataStatus.equalsIgnoreCase("waitCheck"))) {
        //审核通过或审核中不能编辑
        mMenuType = CHECK;
      }
      if (mFrom != null && (mFrom.equalsIgnoreCase(CheckOutListFragment.TODO))) {
        //待办流程中:  只允许修改
        mMenuType = ADD;
      }
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_save_delete, menu);
    switch (mMenuType) {
      case ADD:
        //添加时没有删除,只可以保存
        menu.getItem(1).setVisible(false).setEnabled(false);
        break;
      case CHECK:
        //审核中或审核通过时不可编辑
        menu.getItem(0).setVisible(false).setEnabled(false);
        menu.getItem(1).setVisible(false).setEnabled(false);
        break;
      case EDIT:
        //草稿和审核通过可编辑

        break;
      default:
        break;
    }
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        return true;
      case R.id.menu_item_save:
        //保存
        if (isCorrectInput()) {
          volleyPostSave();
        }
        return true;
      case R.id.menu_item_delete:
        //删除
        DialogFragment dialog = BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm);
        FragmentManager fm = getActivity().getSupportFragmentManager();
        dialog.setTargetFragment(this, REQUEST_DELETE);
        dialog.show(fm, "");
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_check_out, container, false);
    findViews(view);
    bindData();
    return view;
  }

  private void findViews(View v) {

    mEtReason = (EditText) v.findViewById(R.id.et_overTimeReason_checkOver);

    RadioGroup mRgOut = (RadioGroup) v.findViewById(R.id.rg_type);
    RadioButton mRbApplyOut = (RadioButton) v.findViewById(R.id.rb_apply);
    RadioButton mRbSupplyOut = (RadioButton) v.findViewById(R.id.rb_supply);
    mRbApplyOut.setText(R.string.applyOut);
    mRbSupplyOut.setText(R.string.supplyOut);
    TextView llMiddleLine = (TextView) v.findViewById(R.id.ll_line);
    mRgOut.setVisibility(View.GONE);
    llMiddleLine.setVisibility(View.VISIBLE);

    mTvBeginTimeTitle = (TextView) v.findViewById(R.id.tv_beginTimeTitle);
    mTvEndTimeTitle = (TextView) v.findViewById(R.id.tv_endTimeTitle);
    mTvActualStartTime = (TextView) v.findViewById(R.id.tv_actualBeginTime_checkOver);
    mTvActualEndTime = (TextView) v.findViewById(R.id.tv_actualEndTime_checkOver);
    mEtActualHours = (EditText) v.findViewById(R.id.et_actualOverTimeHours_checkOver);
    mTv0utHours = (TextView) v.findViewById(R.id.tv_outHours);

    mTvActualStartTime.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(mTvActualStartTime.getText().toString().trim(), R.string.chooseTime,
            REQUEST_ACTUAL_DATE_START);
      }
    });
    mTvActualEndTime.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {

        showDialog(mTvActualEndTime.getText().toString().trim(), R.string.chooseTime,
            REQUEST_ACTUAL_DATE_END);
      }
    });

    if (mMenuType == CHECK) {
      mEtReason.setEnabled(false);
      mTvActualStartTime.setEnabled(false);
      mTvActualStartTime.setEnabled(false);
      mTvActualEndTime.setEnabled(false);
      mEtActualHours.setEnabled(false);
      //            mRbApplyOut.setEnabled(false);
      //            mRbSupplyOut.setEnabled(false);
    }

    //        mRgOut.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    //            @Override
    //            public void onCheckedChanged(RadioGroup group, int checkedId) {
    //                switch (checkedId) {
    //                    //申请
    //                    case R.id.rb_apply:
    //                        mIfLaterWriter = "F";
    //                        break;
    //                    //补填
    //                    case R.id.rb_supply:
    //                        mIfLaterWriter = "T";
    //                        break;
    //                    default:
    //                        break;
    //                }
    //                initRadio(mIfLaterWriter);
    //            }
    //        });

    initRadio(mIfLaterWriter);
  }

  /**
   * 初始化RadioGroup
   */
  private void initRadio(String ifLaterWriter) {

    if ("F".equalsIgnoreCase(ifLaterWriter)) {
      //申请
      mTvBeginTimeTitle.setText(R.string.planBeginTime);
      mTvEndTimeTitle.setText(R.string.planEndTime);
      mTvActualStartTime.setHint(R.string.planBeginTimeHint);
      mTvActualEndTime.setHint(R.string.planEndTimeHint);
      mTvActualEndTime.setHint(R.string.planEndTimeHint);
      mTv0utHours.setText(R.string.planOutHours);
    }
    if ("T".equalsIgnoreCase(ifLaterWriter)) {
      //补填
      mTvBeginTimeTitle.setText(R.string.actualBeginTime);
      mTvEndTimeTitle.setText(R.string.actualEndTime);
      mTvActualStartTime.setHint(R.string.actualBeginTimeHint);
      mTvActualEndTime.setHint(R.string.actualEndTimeHint);
      mTv0utHours.setText(R.string.actualOutHours);
    }
  }

  private void bindData() {
    if (mcontent != null) {

      mEtReason.setText(mcontent.getOutworkReason());
      //if ("F".equalsIgnoreCase(mIfLaterWriter)) {
      //  mTvActualStartTime.setText(mcontent.getPlanSTime());
      //  mTvActualEndTime.setText(mcontent.getPlanETime());
      //  mEtActualHours.setText(mcontent.getPanOutNum());
      //}
      //if ("T".equalsIgnoreCase(mIfLaterWriter)) {
      mTvActualStartTime.setText(mcontent.getActSTime());
      mTvActualEndTime.setText(mcontent.getActETime());
      mEtActualHours.setText(mcontent.getActOutNum());
      //}
    } else {

      mEtActualHours.setText("0.0");
    }
  }

  private void showDialog(String startDate, int titleId, int requestCode) {

    Date date = DateUtil.stringToDate(startDate);
    if (null == date) {
      date = new Date();
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    DialogFragment dialog = BaseTimeDialogFragment.newInstance(date, titleId);
    dialog.setTargetFragment(this, requestCode);
    dialog.show(fm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) return;
    String startDate;// 开始时间
    String endDate;// 结束时间

    if (requestCode == REQUEST_ACTUAL_DATE_START) {
      Date resultData = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);

      String dateString = DateUtil.dateToString(resultData);

      mTvActualStartTime.setText(dateString);
      startDate = mTvActualStartTime.getText().toString().trim();
      endDate = mTvActualEndTime.getText().toString().trim();
      // 获取工时
      getWorkHours(requestCode, startDate, endDate);
    }
    if (requestCode == REQUEST_ACTUAL_DATE_END) {
      Date resultData = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);

      String dateString = DateUtil.dateToString(resultData);

      mTvActualEndTime.setText(dateString);
      startDate = mTvActualStartTime.getText().toString().trim();
      endDate = mTvActualEndTime.getText().toString().trim();
      // 获取工时
      getWorkHours(requestCode, startDate, endDate);
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  public boolean isCorrectInput() {
    // 验证文本信息
    String reasonString = mEtReason.getText().toString().trim();
    String actualBeginTime = mTvActualStartTime.getText().toString().trim();
    String actualEndTime = mTvActualEndTime.getText().toString().trim();
    String outHours = mEtActualHours.getText().toString().trim();
    if (TextUtils.isEmpty(reasonString)) {
      ToastUtil.show(R.string.no_content);
      return false;
    }

    if (TextUtils.isEmpty(actualEndTime)) {
      ToastUtil.show(R.string.choseEndDate);
      return false;
    }
    if (TextUtils.isEmpty(actualBeginTime)) {
      ToastUtil.show(R.string.choseBeginDate);
      return false;
    }
    if (!DateUtil.before(actualBeginTime, actualEndTime)) {
      ToastUtil.show(R.string.realEndTimeAfterRealStartTime);
      return false;
    }
    if (TextUtils.isEmpty(outHours)) {
      ToastUtil.show(R.string.no_out_hours);
      return false;
    }

    return true;
  }

  private void volleyPostSave() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_OUT_SAVE);
    HashMap<String, String> params = new HashMap<>();
    params.put("pid", mPid);
    params.put("id", mId);
    params.put("outworkReason", mEtReason.getText().toString());
    //params.put("ifLaterWrite", mIfLaterWriter);

    if ("F".equalsIgnoreCase(mIfLaterWriter)) {
      //申请外出
      params.put("planSTime", mTvActualStartTime.getText().toString());
      params.put("planETime", mTvActualEndTime.getText().toString());
      params.put("panOutNum", mEtActualHours.getText().toString());
    }
    if ("T".equalsIgnoreCase(mIfLaterWriter)) {
      //补填外出
      params.put("actSTime", mTvActualStartTime.getText().toString());
      params.put("actETime", mTvActualEndTime.getText().toString());
      params.put("actOutNum", mEtActualHours.getText().toString());
    }
    //判断 待办流程中实际时间确认
    if (mFrom != null && mFrom.equalsIgnoreCase(CheckOutListFragment.TODO)) {
      params.put("isFlow", String.valueOf(true));
    }
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getVolleyResponce());
  }

  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_OUT_DEL);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getVolleyResponce());
  }

  private VolleyResponse getVolleyResponce() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          String successType = successsMessage.getResult();
          if (successType.equals("1")) {
            ToastUtil.show(R.string.success_operation);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            ToastUtil.show(successsMessage.getMessage());
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }
    };
  }

  private void getWorkHours(final int requestCode, String startTime, String endTime) {

    if (TextUtils.isEmpty(startTime) || TextUtils.isEmpty(endTime)) {
      return;
    }
    if (DateUtil.before(endTime, startTime)) {
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_OVER_WORKHOUR);
    HashMap<String, String> params = new HashMap<>();
    params.put("sTime", startTime);
    params.put("eTime", endTime);
    MyUtils.showDialogLoading(getActivity(), R.string.loadingWorkHour);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) {
        MyUtils.dismissDialog();
        try {
          SuccessMessage successMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          if (successMessage.getResult().equals(SuccessMessage.SUCCESS)) {
            String message = successMessage.getMessage();

            if (requestCode == REQUEST_ACTUAL_DATE_START
                || requestCode == REQUEST_ACTUAL_DATE_END) {
              mEtActualHours.setText(message);
            }
          }
        } catch (Exception e) {
          LogUtil.e("workTimeOverError=" + e, e);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.dismissDialog();
      }
    });
  }

  public static CheckOutNewFragment newInstance(CheckOutListContent content, String pid,
      String ifLaterWrite) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    args.putSerializable(EXTRA_IFLATERWRITER, ifLaterWrite);
    args.putSerializable(EXTRA_PID, pid);
    CheckOutNewFragment fragment = new CheckOutNewFragment();
    fragment.setArguments(args);
    return fragment;
  }

  public static CheckOutNewFragment newInstance(CheckOutListContent content, String pid,
      String ifLaterWrite, String from) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    args.putSerializable(EXTRA_FROM, from);
    args.putSerializable(EXTRA_PID, pid);
    args.putSerializable(EXTRA_IFLATERWRITER, ifLaterWrite);
    CheckOutNewFragment fragment = new CheckOutNewFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
